package com.hxz.graduationdesign.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public final class SentimentAnalyzer {
    // 单例实例
    private static final SentimentAnalyzer INSTANCE = new SentimentAnalyzer();
    private static final StopWordUtils STOP_WORD_UTILS = StopWordUtils.getInstance();

    // 情感词典
    private final Set<String> positiveWords;
    private final Set<String> negativeWords;
    private final Set<String> negationWords = new HashSet<>(Arrays.asList(
            "不", "没", "没有", "无", "非", "莫", "勿", "未", "否", "别", "不要"
    ));

    private SentimentAnalyzer() {
        this.positiveWords = loadDictionary("/text/sentiment/正面评价词语（中文）.txt");
        this.positiveWords.addAll(loadDictionary("/text/sentiment/正面情感词语（中文）.txt"));
        this.negativeWords = loadDictionary("/text/sentiment/负面评价词语（中文）.txt");
        this.negativeWords.addAll(loadDictionary("/text/sentiment/负面情感词语（中文）.txt"));
    }

    public static SentimentAnalyzer getInstance() {
        return INSTANCE;
    }
    private Set<String> loadDictionary(String resourcePath) {
        Set<String> words = new HashSet<>();
        try (InputStream is = getClass().getResourceAsStream(resourcePath);
             BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            String line;
            // 跳过第一行（标题行）
            if (reader.ready()) reader.readLine();
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty()) {
                    // 提取词语（忽略可能的数字部分）
                    String word = line.split("\\s+")[0].trim();
                    words.add(word);
                }
            }
        } catch (IOException | NullPointerException e) {
            throw new RuntimeException("Failed to load dictionary: " + resourcePath, e);
        }
        return words;
    }

    public String analyze(String text) {
        if (text == null || text.trim().isEmpty()) {
            return "中立";
        }

        String filteredText = STOP_WORD_UTILS.filterStopWords(text);

        int positiveCount = 0;
        int negativeCount = 0;
        boolean negated = false;


        for (int i = 0; i < filteredText.length(); i++) {

            String currentChar = filteredText.substring(i, i + 1);
            if (negationWords.contains(currentChar)) {
                negated = true;
                continue;
            }


            for (int len = 4; len >= 1; len--) {
                if (i + len > filteredText.length()) continue;

                String word = filteredText.substring(i, i + len);


                if (STOP_WORD_UTILS.isStopWord(word)) {
                    i += len - 1;
                    negated = false;
                    break;
                }

                if (positiveWords.contains(word)) {
                    if (negated) {
                        negativeCount++;
                    } else {
                        positiveCount++;
                    }
                    i += len - 1; // 跳过已匹配的部分
                    negated = false;
                    break;
                } else if (negativeWords.contains(word)) {
                    if (negated) {
                        positiveCount++;
                    } else {
                        negativeCount++;
                    }
                    i += len - 1;
                    negated = false;
                    break;
                }
            }

            negated = false;
        }

        // 判断结果
        if (positiveCount > negativeCount) {
            return "积极";
        } else if (negativeCount > positiveCount) {
            return "消极";
        } else {
            return "中立";
        }
    }

    public SentimentResult analyzeWithConfidence(String text) {
        if (text == null || text.trim().isEmpty()) {
            return new SentimentResult("中立", 0);
        }

        // 先过滤停用词
        String filteredText = STOP_WORD_UTILS.filterStopWords(text);

        int positiveCount = 0;
        int negativeCount = 0;
        boolean negated = false;

        // 情感分析
        for (int i = 0; i < filteredText.length(); i++) {
            String currentChar = filteredText.substring(i, i + 1);
            if (negationWords.contains(currentChar)) {
                negated = true;
                continue;
            }

            for (int len = 4; len >= 1; len--) {
                if (i + len > filteredText.length()) continue;

                String word = filteredText.substring(i, i + len);

                // 跳过停用词
                if (STOP_WORD_UTILS.isStopWord(word)) {
                    i += len - 1;
                    negated = false;
                    break;
                }

                if (positiveWords.contains(word)) {
                    if (negated) {
                        negativeCount++;
                    } else {
                        positiveCount++;
                    }
                    i += len - 1;
                    negated = false;
                    break;
                } else if (negativeWords.contains(word)) {
                    if (negated) {
                        positiveCount++;
                    } else {
                        negativeCount++;
                    }
                    i += len - 1;
                    negated = false;
                    break;
                }
            }
            negated = false;
        }

        // 计算置信度
        int total = positiveCount + negativeCount;
        if (total == 0) {
            return new SentimentResult("中立", 0);
        }

        double confidence;
        String sentiment;
        if (positiveCount > negativeCount) {
            sentiment = "积极";
            confidence = (double) positiveCount / total;
        } else if (negativeCount > positiveCount) {
            sentiment = "消极";
            confidence = (double) negativeCount / total;
        } else {
            sentiment = "中立";
            confidence = 0.5;
        }

        return new SentimentResult(sentiment, confidence);
    }

    public static class SentimentResult {
        private final String sentiment;
        private final double confidence;

        public SentimentResult(String sentiment, double confidence) {
            this.sentiment = sentiment;
            this.confidence = confidence;
        }

        public String getSentiment() {
            return sentiment;
        }

        public double getConfidence() {
            return confidence;
        }

        @Override
        public String toString() {
            return String.format("%s (%.2f)", sentiment, confidence);
        }
    }

}